from stark.service.v1 import StarkHandler, get_choice_text, StarkModelForm
from django.urls import re_path
from django import forms
from web import models
from django.shortcuts import HttpResponse
from .base import  PermissionHandler

class PaymentRecordModelForm(StarkModelForm):
    """对于已经有学员信息的添加缴费记录，显示的form表单"""

    class Meta:
        model = models.PaymentRecord
        fields = ['pay_type', 'paid_fee', 'class_list', 'note']


class StudentPaymentRecordModelForm(StarkModelForm):
    """对于没有学员信息的添加缴费记录，显示的form表单"""
    qq = forms.CharField(label='QQ号', max_length=32)
    mobile = forms.CharField(label='手机号码', max_length=32)
    emergency_contract = forms.CharField(label='紧急联系人电话', max_length=32)

    class Meta:
        model = models.PaymentRecord
        fields = ['pay_type', 'paid_fee', 'class_list', 'qq', 'mobile', 'emergency_contract', 'note']


class PaymentRecordHandler(PermissionHandler,StarkHandler):
    # model_form_class = PaymentRecordModelForm

    def get_model_form_class(self, is_add, request, pk, *args, **kwargs):
        # 如果当前客户有学生信息，则使用PaymentRecordModelForm 否则时使用StudentPaymentRecordModelForm
        customer_id = kwargs.get('customer_id')
        student_exists = models.Student.objects.filter(customer_id=customer_id).exists()
        if student_exists:
            return PaymentRecordModelForm
        else:
            return StudentPaymentRecordModelForm

    field_name_list = [get_choice_text('费用类型', 'pay_type'),
                       'paid_fee', 'class_list', 'consultant',
                       get_choice_text('缴费状态', 'confirm_status')]

    def get_field_name_list(self,request,*args,**kwargs):
        # 为当前也显示的列进行扩展需求
        value = []
        if self.field_name_list:
            value.extend(self.field_name_list)
        return value

    def get_urls(self):
        patterns = [
            re_path('list/(?P<customer_id>\d+)/', self.wrapper(self.changelist_view), name=self.get_list_url_name),
            re_path('add/(?P<customer_id>\d+)/', self.wrapper(self.add_view), name=self.get_add_url_name),
        ]
        patterns.extend(self.extra_urls())  # 新增的url 扩增
        return patterns

    def get_queryset(self, request, *args, **kwargs):
        """获取相应的queryset对象集合，用于显示的数据"""
        customer_id = kwargs.get('customer_id')
        current_user_id = request.session['current_user_id']
        obj = self.model_class.objects.filter(customer_id=customer_id, customer__consultant_id=current_user_id)
        return obj

    #
    def save(self, request, form, is_update, *args, **kwargs):
        """保存前校验数据是否正确，并设置默认值"""
        customer_id = kwargs.get('customer_id')
        current_user_id = request.session.get('current_user_id')
        obj = models.Customer.objects.filter(id=customer_id, consultant_id=current_user_id).exists()
        if not obj:
            return HttpResponse('非法操作')
        form.instance.customer_id = customer_id
        form.instance.consultant_id = current_user_id
        # 创建缴费记录信息
        form.save()
        # 创建学员信息
        class_list = form.cleaned_data['class_list']
        student_fetch = models.Student.objects.filter(customer_id=customer_id).first()
        if not student_fetch:
            qq = form.cleaned_data['qq']
            mobile = form.cleaned_data['mobile']
            emergency_contract = form.cleaned_data['emergency_contract']
            student_obj = models.Student.objects.create(customer_id=customer_id,
                                                        qq=qq,
                                                        mobile=mobile,
                                                        emergency_contract=emergency_contract)
            student_obj.class_list.add(class_list.id)  # 添加课程信息
        else:
            student_fetch.class_list.add(class_list.id)
